﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using DotNet.Common;
using System.Drawing;
using System.Threading;
using System.Drawing.Imaging;
public partial class GetThumbImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["filePath"] != null && Request.QueryString["thumbWidth"]!=null)
        {
            if (Request.QueryString["filePath"].ToString() != "" && Request.QueryString["thumbWidth"].ToString() != "")
            {
                if (Convert.ToInt32(Request.QueryString["thumbWidth"]) > 500 && Request.QueryString["filePath"].ToString().Length<100)
                {
                    return;
                }
                //Thread.Sleep(100);
                string fileName = Server.MapPath("~" + Request["filePath"].ToString());
                if (System.IO.File.Exists(fileName))
                {
                    int thumbWidth = int.Parse(Request["thumbWidth"]);
                    MakeThumbnail(fileName, thumbWidth);
                    //System.Drawing.Image img = GetThumbnail(fileName, thumbWidth);
                    //if (img != null)
                    //{
                    //    img.Save(Response.OutputStream, ImageFormat.Jpeg);
                    //    img.Dispose();
                    //    Response.End();
                    //}
                }
                
            }
        }
        
    }
    #region 生成缩略图 方式一

    /**/
    /// <summary> 
    /// 生成缩略图 
    /// </summary> 
    /// <param name="originalImagePath">源图路径（物理路径）</param> 
    /// <param name="width">缩略图宽度</param>    
    public  void MakeThumbnail(string originalImagePath, int imageMaxSize)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
        int width = imageMaxSize;
        int height = imageMaxSize;
        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        string mode = "H";
        if (ow > oh) { mode = "W"; }
        switch (mode)
        {
            case "HW"://指定高宽缩放（可能变形）                 
                break;
            case "W"://指定宽，高按比例                     
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H"://指定高，宽按比例 
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut"://指定高宽裁减（不变形）                 
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }


        //新建一个bmp图片 
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(imageMaxSize, imageMaxSize);

        //新建一个画板 
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法 
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度 
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        //清空画布并以透明背景色填充 
        g.Clear(System.Drawing.Color.White);

        //在指定位置并且按指定大小绘制原图片的指定部分 
        g.DrawImage(originalImage, new Rectangle((imageMaxSize - towidth) / 2, (imageMaxSize - toheight) / 2, towidth, toheight),
            new System.Drawing.Rectangle(0, 0, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
        // g.DrawString("aaaaaaaaaaaaaaaaaaaaaa", new Font("华文彩云", 12), new SolidBrush(Color.FromArgb(180, 70, 140, 140)), new PointF(0, 0));
      
        try
        {
            //以jpg格式保存缩略图 
            System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
           
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            System.Web.HttpContext.Current.Response.ClearContent();
            System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            ms.Close();
            
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
           
        }
    }
    #endregion

    #region 生成缩略图 带图片水印 方式二

    /**/
    /// <summary> 
    /// 生成缩略图 
    /// </summary> 
    /// <param name="originalImagePath">源图路径（物理路径）</param> 
    /// <param name="width">缩略图宽度</param>    
    public void MakeThumbnail(string originalImagePath, int imageMaxSize, bool water)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
        int width = imageMaxSize;
        int height = imageMaxSize;
        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        string mode = "H";
        if (ow > oh) { mode = "W"; }
        switch (mode)
        {
            case "HW"://指定高宽缩放（可能变形）                 
                break;
            case "W"://指定宽，高按比例                     
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H"://指定高，宽按比例 
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut"://指定高宽裁减（不变形）                 
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }


        //新建一个bmp图片 
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(imageMaxSize, imageMaxSize);

        //新建一个画板 
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法 
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度 
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        //清空画布并以透明背景色填充 
        g.Clear(System.Drawing.Color.White);

        //在指定位置并且按指定大小绘制原图片的指定部分 
        g.DrawImage(originalImage, new Rectangle((imageMaxSize - towidth) / 2, (imageMaxSize - toheight) / 2, towidth, toheight),
            new System.Drawing.Rectangle(0, 0, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
        if (water && File.Exists(Server.MapPath(@"~\UploadFiles\1.png")))
        {
            #region 图片水印
            //新建一个Image属性 
            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
            float[][] colorMatrixElements = { 
                                                     new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                     new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                     new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                     new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
                                                     new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                                    };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
            //将颜色矩阵添加到属性
            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Server.MapPath(@"~\UploadFiles\1.png"));
            if (copyImage.Width > bitmap.Width || copyImage.Height > bitmap.Height)
            {
                System.Drawing.Image.GetThumbnailImageAbort callb = null;
                //对水印图片生成缩略图,缩小到原图得1/4 
                copyImage = copyImage.GetThumbnailImage(bitmap.Width, bitmap.Height, callb, new System.IntPtr());
            }
            g.DrawImage(copyImage, new System.Drawing.Rectangle((bitmap.Width - copyImage.Width) - 0, (bitmap.Height - copyImage.Height) - 0, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);
            //image.Save(Path_syp, ImageFormat.Jpeg);
            #endregion
        }
        // g.DrawString("aaaaaaaaaaaaaaaaaaaaaa", new Font("华文彩云", 12), new SolidBrush(Color.FromArgb(180, 70, 140, 140)), new PointF(0, 0));

        try
        {
            //以jpg格式保存缩略图 
            System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            System.Web.HttpContext.Current.Response.ClearContent();
            System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            ms.Close();

        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();

        }
    }
    #endregion

    #region 方式2
    /// <summary>
    /// 图片缩放
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="imageMaxSize">图片最大尺寸</param>
    /// <returns>Image对象</returns>
    public  System.Drawing.Image GetThumbnail(string filePath, int imageMaxSize)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(filePath);

        int width = imageMaxSize;
        int height = imageMaxSize;
        int towidth = width;
        int toheight = height;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        string mode = "H";
        if (ow > oh) { mode = "W"; }
        System.Drawing.Image bitmap;
        switch (mode)
        {
            case "W"://【指定宽，高按比例】
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H"://【指定高，宽按比例】
                towidth = originalImage.Width * height / originalImage.Height;
                break;
        }
        bitmap = new Bitmap(imageMaxSize, imageMaxSize);
        Graphics g = Graphics.FromImage(bitmap);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

        g.Clear(Color.White);
        g.DrawImage(originalImage, new Rectangle((imageMaxSize - towidth) / 2, (imageMaxSize - toheight) / 2, towidth, toheight), new Rectangle(0, 0,ow, oh), GraphicsUnit.Pixel);
       
        originalImage.Dispose();
        return bitmap;
    }
    #endregion

    
    #region
    /// <summary>
    /// 会产生graphics异常的PixelFormat
    /// </summary>
    private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare, PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed, PixelFormat.Format8bppIndexed };
    /// <summary>
    /// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
    /// 无法从带有索引像素格式的图像创建graphics对象
    /// </summary>
    /// <param name="imgPixelFormat">原图片的PixelFormat</param>
    /// <returns></returns>
    private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
    {
        foreach (PixelFormat pf in indexedPixelFormats)
        {
            if (pf.Equals(imgPixelFormat)) return true;
        }

        return false;
    }

    #endregion


}
